package com.bingkaimedia.merchantbeta.app;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.bingkaimedia.merchantbeta.R;
import com.bingkaimedia.merchantbeta.libs.JSONfunctions;
import com.bingkaimedia.merchantbeta.libs.SessionManager;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MenuKanan extends ListFragment {

	// XML node keys
		//static final String KEY_SONG = "song"; // parent node
		public static final String KEY_CATEGORY = "voucher_category";  
		public static final String KEY_CATEGORY_ID = "id_voucher_category";  
		
		private String xml_programs_cat; 
		private String xml_programs_cat_id; 
		
		private static String session_userid;
		private static String session_username;
		private static String session_password;
		private static String session_email;
		private static String session_country;
		private static String session_country_name;
		private static String session_city;
		private static String session_city_name;
		private static String session_checked;
		private static String session_channel;
		private static String session_category;
		private static String session_category_name;
	    
		
		static final int MENU_MANUAL_REFRESH = 0;
		static final int MENU_DISABLE_SCROLL = 1;
		static final int MENU_SET_MODE = 2;
		static final int MENU_DEMO = 3;
		
		private PullToRefreshListView mPullRefreshListView;
		ListView actualListView;

		private ArrayList<Category> categorylist;
		private String id_;


	private int count;
	private String json;
	private String result;
	private JSONObject jsonobject;
	public String code;
	public String msg;
	 
	SampleAdapter adapter;
	
	

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		adapter = new SampleAdapter(getActivity());

	    categorylist = new ArrayList<Category>();
		new loadData().execute();
		
		/*
		adapter.add(new SampleItem("All", R.drawable.diskonion_iconpanah2));
		adapter.add(new SampleItem("Fashion & Jewelry", R.drawable.diskonion_iconpanah2));
		adapter.add(new SampleItem("Food & Beverage", R.drawable.diskonion_iconpanah2));
		adapter.add(new SampleItem("Beauty & Wellness", R.drawable.diskonion_iconpanah2));
		adapter.add(new SampleItem("Gadget, Tech & Oto", R.drawable.diskonion_iconpanah2));
		adapter.add(new SampleItem("Health & Education", R.drawable.diskonion_iconpanah2));
		adapter.add(new SampleItem("Hobby & Leisure", R.drawable.diskonion_iconpanah2));
		adapter.add(new SampleItem("Home Appliance", R.drawable.diskonion_iconpanah2));
		adapter.add(new SampleItem("Service", R.drawable.diskonion_iconpanah2));
		*/  
		setListAdapter(adapter);
	}

	private class SampleItem {
		public String tag;
		public int iconRes;
		public SampleItem(String tag, int iconRes) {
			this.tag = tag; 
			this.iconRes = iconRes;
		}
	}

	public class SampleAdapter extends ArrayAdapter<SampleItem> {

		public SampleAdapter(Context context) {
			super(context, 0);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_list_menu, null);
			}
			ImageView icon = (ImageView) convertView.findViewById(R.id.row_icon);
			icon.setImageResource(getItem(position).iconRes);
			TextView title = (TextView) convertView.findViewById(R.id.row_title);
			title.setText(getItem(position).tag);

			return convertView;
		}

	}
	
	
	@SuppressLint("NewApi")
	private class loadData extends AsyncTask<Void, Void, Void>  {

		@Override
		protected void onPreExecute() {
			 
		}

		protected Void doInBackground(Void... unused) {
			code="99";
			msg="Not connected to server";
			
	    	Global.URL = Global.link_category;
			//////System.out.println(Global.URL);  
			Global.URL = Global.URL.replace(" ", "%20");
			 
			//////System.out.println("Mulai do in background");
 
			try{ 
				json=JSONfunctions.getStringContent(Global.URL);
				jsonobject=new JSONObject(json); 
				code=jsonobject.getString("code");
				msg=jsonobject.getString("msg");
				 
			}
			catch (Exception e) 
			{
				e.printStackTrace();
				////System.out.println("catch code msg");
				////System.out.println(e); 
				//Toast.makeText(getApplicationContext(), "Something wrong in your connection", Toast.LENGTH_LONG).show();
			
			}
			
			////System.out.println("code "+code);
			if(code.equalsIgnoreCase("99")){
				try{ 
					////System.out.println(Global.URL);
					//json=JSONfunctions.getStringContent2(Global.URL);
					////System.out.println(json); 
					 
				}
				catch (Exception e) 
				{
					e.printStackTrace();
					////System.out.println("catch 1");
					////System.out.println(e);
 
					//Toast.makeText(getApplicationContext(), "Something wrong in your connection (1)", Toast.LENGTH_LONG).show();
				
				}
			}
		  
			 
			return null;
		}
		
		
		protected void onPostExecute(Void unused) {
			  
			count = 0;  
			result = json;
			
			if(code.equalsIgnoreCase("0")){
				
				Toast.makeText(getActivity().getBaseContext(), msg, Toast.LENGTH_LONG).show();
			}
			else{  
				try{
					
			      	JSONArray jArray = new JSONArray(result);
			      	JSONObject json_data=null; 
			      	//////System.out.println("array length");
			      	//////System.out.println(jArray.length());
			      	
			      	for(int i=0;i<jArray.length();i++){
						json_data = jArray.getJSONObject(i);  
						xml_programs_cat = json_data.getString(KEY_CATEGORY);  
						xml_programs_cat_id = json_data.getString(KEY_CATEGORY_ID);
						
						//////System.out.println("db");
						//////System.out.println(xml_programs_cat);  
						//////System.out.println(xml_programs_cat_id);  
						adapter.add(new SampleItem(xml_programs_cat, R.drawable.diskonion_icon_panah2));
						
						Category cate = new Category(xml_programs_cat_id, xml_programs_cat);
						categorylist.add(cate);  
			      	} 
			      	
				}catch(JSONException e1){ 
					////System.out.println("catch 2");
					////System.out.println(e1);
					Toast.makeText(getActivity().getBaseContext(), "Something wrong in your connection (2)", Toast.LENGTH_LONG).show();
				}catch (ParseException e1){ 
					////System.out.println("catch 3");
					////System.out.println(e1);
					Toast.makeText(getActivity().getBaseContext(), "Something wrong in your connection (3)", Toast.LENGTH_LONG).show();	
				}  
			} 
		}
	}
	
	
	
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		 
		Intent extras = getActivity().getIntent();
		  
		Intent intent = null;
		//((MenuLeft)getActivity()).getSlideoutHelper().close();
		SessionManager session;
        session = new SessionManager(getActivity().getApplicationContext());
        HashMap<String, String> user = session.getUserDetails(); 
        
        session_userid = user.get(SessionManager.id_users);
	    session_username = user.get(SessionManager.username);
	    session_password = user.get(SessionManager.password);
	    session_email = user.get(SessionManager.email);
	    session_country = user.get(SessionManager.country);
	    session_country_name = user.get(SessionManager.country_name);
	    session_city = user.get(SessionManager.city);
	    session_city_name = user.get(SessionManager.city_name);
	    session_checked = user.get(SessionManager.checked);
	    session_channel = user.get(SessionManager.channel);
	    session_category = "";
	    session_category_name = "";
	    
	    //////System.out.println("session menu kanan");
	    //////System.out.println(session_userid);
	    //////System.out.println(session_username);
	    //////System.out.println(session_password);
	    //////System.out.println(session_email);
	    //////System.out.println(session_country);
	    //////System.out.println(session_country_name);
	    //////System.out.println(session_city);
	    //////System.out.println(session_city_name);
	    //////System.out.println(session_checked);
	    //////System.out.println(session_channel);
	    //////System.out.println(session_category);
	    //////System.out.println(session_category_name);
		
		//////System.out.println("print array list");
		int x = position+1;
		String selec = String.valueOf(x);
		//////System.out.println(selec);
		//////System.out.println(categorylist.size());
		//////System.out.println("===");
		String phonecode ="";
		Boolean exist = false;
		for(int i = 0; i < categorylist.size(); i++) 
		{
			
			String select_array = categorylist.get(i).getid_voucher_category().toString();
			if(select_array.equalsIgnoreCase(selec)){
				//////System.out.println((categorylist.get(i).getvoucher_category()).toString());
				//////System.out.println((categorylist.get(i).getid_voucher_category()).toString());
				
				session_category = categorylist.get(i).getid_voucher_category().toString();
				session_category_name = categorylist.get(i).getvoucher_category().toString();
				exist=true;
	            break;
			}
			
		} 
		
		if(exist) {
			session_category_name = session_category_name;
		} else {
		     
		}
		
		//////System.out.println(session_city);
		//////System.out.println(session_city_name);
		//////System.out.println(session_category);
		//////System.out.println(session_category_name);
		
		session.createLoginSession(session_userid, session_username, session_password, session_email, session_country, session_country_name, session_city, session_city_name, session_checked, session_channel, session_category,session_category_name);
		intent = new Intent(getActivity().getApplicationContext(),Home.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}
	 
}
